package com.classroom.langchain.demo.controller;

import com.classroom.langchain.demo.aiservice.StreamConsultantService;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/stream")
public class StreamDemoController {


//    http://localhost:8080/stream/chat?message=柳颜漂不漂亮
//    http://localhost:8080/stream/chatApi?message=柳颜漂不漂亮


    @Autowired
    private StreamConsultantService streamConsultantService;
//    @RequestMapping(value = "/chat", produces = MediaType.TEXT_HTML_VALUE + ";charset=UTF-8")
    @RequestMapping(value = "/chat")
    public Flux<String> chat(@RequestParam("memoryId") String memoryId,@RequestParam("message") String message) {
        try {
            Flux<String>  result = streamConsultantService.chat(memoryId,message);
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @Resource
    private StreamingChatModel streamingChatModel;

    @RequestMapping(value = "/chatApi")
    public Flux<String> chatApi(@RequestParam("message") String message) {
        try {
            return Flux.create(emitter -> {
                streamingChatModel.chat(message, new StreamingChatResponseHandler() {
                    @Override
                    public void onPartialResponse(String partialResponse) {
                        emitter.next(partialResponse);
                    }

                    @Override
                    public void onCompleteResponse(ChatResponse completeResponse) {
                        emitter.complete();
                    }

                    @Override
                    public void onError(Throwable error) {
                        emitter.error(error);
                    }
                });
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}